package com.itheima.d2_reflect_test;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.reflect.Field;

/*
    对象框架
    目标：保存任意对象的字段和其数据到文件中去
 */
public class ObjectFrame {


    public static void saveobj(Object obj) throws IOException, Exception {

        BufferedWriter bw = new BufferedWriter(new FileWriter("user.txt",true));

        Class<?> clazz = obj.getClass();
        bw.write("=====================" + clazz.getSimpleName() + "=====================");
        bw.newLine();
        bw.flush();
        //获取clazz的成员变量
        Field[] declaredFields = clazz.getDeclaredFields();
        //遍历数组，获得每一个成员变量
        for (Field f : declaredFields) {
            f.setAccessible(true);//暴力反射
            //变量名
            String name = f.getName();
            //变量值
            Object o = f.get(obj);
            bw.write(name + ":" + o);
            bw.newLine();
            bw.flush();
        }
        bw.close();
    }
}
